using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using NBear.Common;

namespace NBear.IoC.Service.Services
{
    [Serializable]
    public abstract class BaseService : MarshalByRefObject, IService, ILogable
    {
        private Guid clientId;

        protected void WriteLog(string logInfo)
        {
            if (OnLog != null)
            {
                OnLog(logInfo);
            }
        }

        protected string serviceName;
        protected IServiceMQ mq;

        protected abstract  ResponseMessage Run(RequestMessage msg);

        public BaseService(string serviceName, IServiceMQ mq)
        {
            this.serviceName = serviceName;
            this.mq = mq;
            clientId = Guid.NewGuid();
        }

        #region IService Members

        public Guid ClientId
        {
            get
            {
                return clientId;
            }
        }

        public string ServiceName
        {
            get { return serviceName; }
        }

        public ResponseMessage CallService(RequestMessage msg)
        {
            WriteLog(string.Format("dynamic service({2})[{1}] process(msg->{0})", SerializeHelper.Serialize(msg), clientId, serviceName));
            ResponseMessage retMsg = null;
            try
            {
                retMsg = Run(msg);
            }
            catch (Exception ex)
            {
                WriteLog(string.Format("Error occured at {0}[{1}]: {2}", serviceName, clientId, ex));
                return null;
            }
            WriteLog(string.Format("dynamic service({2})[{1}] return(msg->{0})", SerializeHelper.Serialize(retMsg), clientId, serviceName));
            return retMsg;
        }

        #endregion

        #region MarshalByRefObject

        public override object InitializeLifetimeService()
        {
            return null;
        }

        #endregion

        #region ILogable Members

        public event LogHandler OnLog;

        #endregion
    }
}
